import CryptoJS from '../../../libs/crypto-js/crypto-js';
const db = wx.cloud.database();

Page({
  data: {
    details: [],  // 新闻详情
    textContent: '', // 新闻的纯文本内容
    mediaPath: '', // 上传后的音频路径
  },

  // 页面加载时获取新闻详情
  onLoad(options) {
    const id = options._id; // 获取传递过来的 _id
    this.getNewsDetail(id);
  },

  // 获取新闻详情
  getNewsDetail: function (id) {
    db.collection('news').doc(id).get().then(res => {
      const content = res.data.content;
      const textContent = content.replace(/<[^>]+>/g, ''); // 去除 HTML 标签
      this.setData({
        details: res.data,
        textContent: textContent
      });
    }).catch(err => {
      console.error(err);
    });
  },

  // 检查音频是否已存在
  checkAudioExists: function (newsID) {
    const audioFilesCollection = db.collection('api');
    return audioFilesCollection.where({
      newsID: newsID
    }).get();
  },

  // 生成音频并上传
  getVideo: function () {
    const fileName = `${this.data.details.title}.mp3`; // 使用新闻标题生成文件名
    const encodedFileName = encodeURIComponent(fileName); // 对文件名进行 URL 编码
    const cloudPath = `audio/${encodedFileName}`; // 使用编码后的文件名
    console.log('Encoded cloud path:', cloudPath);

    // 检查音频是否已存在
    const newsID = this.data.details._id;
    this.checkAudioExists(newsID).then(res => {
      if (res.data.length > 0) {
        console.log('音频已存在:', res.data[0].fileID);
        wx.navigateTo({
          url: `../news_voice/news_voice?fileURL=${res.data[0].fileID}&title=${this.data.details.title}`, // 传递 title
        });
      } else {
        console.log('音频不存在，生成新的音频...');
        this.createRequest(cloudPath);
      }
    }).catch(err => {
      console.error('检查音频失败:', err);
    });
  },

  // 请求生成音频
  createRequest: function (cloudPath) {
    const APP_KEY = '5082ddfda482ddc6'; 
    const APP_SECRET = 'bDN4GpfcfDqKKPDar3DSjuIjKX1pO0y9'; 

    const q = this.data.textContent;
    const voiceName = 'youxiaozhi';
    const format = 'mp3';

    const data = {
      q: q,
      speed: 1,
      voiceName: voiceName,
      format: format,
      title: this.data.details.title // Pass the title
    };

    this.addAuthParams(APP_KEY, APP_SECRET, data);

    wx.request({
      url: 'https://openapi.youdao.com/ttsapi',
      method: 'POST',
      data: data,
      responseType: 'arraybuffer',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      success: (res) => {
        this.uploadToCloudStorage(res.data, cloudPath);
      },
      fail: (err) => {
        console.error('请求失败', err);
      },
    });
  },

  // 上传音频到云存储并存入数据库
  uploadToCloudStorage: function (audioData, cloudPath) {
    wx.showLoading({
      title: '正在上传音频...',
    });

    const fileSystemManager = wx.getFileSystemManager();
    const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_audio.mp3`;

    fileSystemManager.writeFile({
      filePath: tempFilePath,
      data: audioData,
      encoding: 'binary',
      success: () => {
        console.log('音频文件成功写入本地临时路径:', tempFilePath);

        wx.cloud.uploadFile({
          cloudPath: cloudPath,
          filePath: tempFilePath,
        }).then(res => {
          console.log('音频上传成功:', res.fileID);

          // 存入新的数据库集合
          const newsID = this.data.details._id;
          this.uploadFileIDToNewDatabase(newsID, res.fileID);

          this.setData({ mediaPath: res.fileID });
          wx.hideLoading();

          // 跳转到播放页面
          wx.navigateTo({
            url: `../news_voice/news_voice?fileURL=${res.fileID}&title=${this.data.details.title}`, // 传递 title
          });
        }).catch(err => {
          console.error('音频上传失败:', err);
          wx.hideLoading();
        });
      },
      fail: (err) => {
        console.error('写入本地文件失败:', err);
        wx.hideLoading();
      },
    });
  },

  // 将文件 ID 存入新的数据库集合
  uploadFileIDToNewDatabase: function (newsID, fileID) {
    const audioFilesCollection = db.collection('api');
    audioFilesCollection.add({
      data: {
        newsID: newsID,
        fileID: fileID,
        createdAt: new Date(), // 可选：创建时间
      },
    }).then(() => {
      console.log('音频文件 ID 添加成功');
    }).catch(err => {
      console.error('音频文件 ID 添加失败:', err);
    });
  },

  // 添加鉴权参数
  addAuthParams: function (appKey, appSecret, params) {
    const q = params.q || params.img;
    const salt = this.generateUUID();
    const curtime = Math.floor(Date.now() / 1000).toString();
    const sign = this.calculateSign(appKey, appSecret, q, salt, curtime);

    params.appKey = appKey;
    params.salt = salt;
    params.curtime = curtime;
    params.signType = 'v3';
    params.sign = sign;
  },

  calculateSign: function (appKey, appSecret, q, salt, curtime) {
    const strSrc = appKey + this.getInput(q) + salt + curtime + appSecret;
    return this.encrypt(strSrc);
  },

  encrypt: function (strSrc) {
    return CryptoJS.SHA256(strSrc).toString(CryptoJS.enc.Hex);
  },

  getInput: function (input) {
    if (!input) return input;
    const inputLen = input.length;
    return inputLen <= 20 ? input : input.substring(0, 10) + inputLen + input.substring(inputLen - 10);
  },

  generateUUID: function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  },
});
